package offer;

public class GetKthFromEnd_22 {

    public ListNode getKthFromEnd(ListNode head, int k) {
        if(head == null) return null;
        ListNode first = head;
        ListNode second = head;
        for (int i = 0; i < k; i++) {
            first = first.next;
        }

        while (first != null){
            first = first.next;
            second = second.next;
        }
        return second;
    }

    public ListNode getKthFromEnd2(ListNode head, int k) {
        if(head == null) return null;
        ListNode first = head;
        ListNode second = head;
        int count = 0;
        for (int i = 0; i < k; i++) {
            if(first == null){
                return null;
            }
            first = first.next;
        }
        // 退出循环fist == null
        while (first != null){
            first = first.next;
            second = second.next;
        }
        return second;
    }

    public ListNode getKthFromEnd3(ListNode head, int k) {
        if(head == null) return null;
        ListNode fast = head;
        ListNode slow = head;
        for (int i = 0; i < k; i++) {
            if(fast == null){
                return null;
            }
            fast = fast.next;
        }
        while (fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;



    }

 public class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }
 }

}
